#!/usr/bin/env bash

#
# created by movee
#

# set -x # Print trace
set -u # Variables can only be used after set.
set -e # Non-zero exit status must be captured.
set -o pipefail # Return exit status of the last successful command in a pipeline.

# paths

function info() {
    datetime=`date "+%Y-%m-%d %H:%M:%S |"`
    echo -e "\033[1;94m${datetime} INFO |\033[0m\033[0;94m $@ \033[0m"
}

function error() {
    datetime=`date "+%Y-%m-%d %H:%M:%S |"`
    echo -e "\033[1;91m${datetime} ERROR |\033[0m\033[1;91m $@ \033[0m" >&2
}

readonly PROJ_NAME="sdn-executor"
readonly BUILD_ROOT_DIR="$( cd $(dirname $0) && pwd -P)"
readonly OUTPUT_DIR="${BUILD_ROOT_DIR}/output"
readonly OUTPUT_BIN_DIR="${OUTPUT_DIR}/bin"
readonly OUTPUT_CONF_DIR="${OUTPUT_DIR}/conf"
readonly OUTPUT_TEMP_DIR="${BUILD_ROOT_DIR}/output_temp"

function calc_cpus() {

    case "`uname`" in
        Linux)
            cpu_cores=`egrep -c 'processor([[:space:]]+):.*' /proc/cpuinfo`
        ;;
        FreeBSD)
            cpu_cores=`sysctl hw.ncpu | awk '{print $2}'`
        ;;
        SunOS)
            cpu_cores=`psrinfo | wc -l`
        ;;
        Darwin)
            cpu_cores=`sysctl hw.ncpu | awk '{print $2}'`
        ;;
        *)
            cpu_cores="2"
        ;;
    esac

    if [ "$cpu_cores" -lt "1" ] ; then
        cpu_cores="1"
    fi

    if [ "$cpu_cores" -lt "3" ] ; then
        cpu_cores="1"
    elif [ "$cpu_cores" -gt "8" ] ; then
        cpu_cores=$(($cpu_cores - 4))
    else
        cpu_cores=$(($cpu_cores - 2))
    fi

}

# 配置java环境以及依赖
function env_init() {
    info "prepare environment......"
}

# 编译生成可执行文件
function build() {

    info "start build ......"

    calc_cpus

    cd ${BUILD_ROOT_DIR}
    go build -o ${PROJ_NAME}
    if [ $? -ne 0 ]; then
        error "build ${BUILD_ROOT_DIR} failed"
        exit 1
    fi

    cd ${BUILD_ROOT_DIR}
    info "build successfully"
}

function pack() {
    info "start packing......"

    rm -rf ${OUTPUT_DIR}
    mkdir -p ${OUTPUT_DIR}
    mkdir -p ${OUTPUT_BIN_DIR}
    mkdir -p ${OUTPUT_CONF_DIR}

    mv ${BUILD_ROOT_DIR}/${PROJ_NAME} ${OUTPUT_BIN_DIR}/
    cp -f ${BUILD_ROOT_DIR}/bin/* ${OUTPUT_BIN_DIR}/
    mv -f ${OUTPUT_BIN_DIR}/supervisor ${OUTPUT_BIN_DIR}/supervisor_${PROJ_NAME}
    cp -f ${BUILD_ROOT_DIR}/conf/* ${OUTPUT_CONF_DIR}/

}

# 清理临时文件
function clean() {
    info "start clean......"

    rm -rf ${OUTPUT_TEMP_DIR}
}

function main() {

    env_init
    build
    pack
    clean

    info "Build done successfully"
}

main "$@"